<template>
  <div class="listener-field-inject">
    <a-form :model="formData" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="字段名称" required>
        <a-input v-model:value="formData.name" />
      </a-form-item>
      <a-form-item label="字段类型" required>
        <a-select v-model:value="formData.type" style="width: 100%">
          <a-select-option value="string">字符串</a-select-option>
          <a-select-option value="expression">表达式</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="字段值" required>
        <a-input v-model:value="formData.value" />
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
import { computed, onMounted, ref, watch } from 'vue'

export default {
  name: 'ListenerFieldInject',
  props: {
    field: {
      type: Object,
      default: () => ({
        name: '',
        type: 'string',
        value: ''
      })
    }
  },
  emits: ['update:field'],
  setup(props, { emit }) {
    const formData = ref({
      name: '',
      type: 'string',
      value: ''
    })

    watch(() => props.field, (val) => {
      if (val) {
        formData.value = { ...val }
      }
    }, { immediate: true })

    watch(() => formData.value, (val) => {
      emit('update:field', val)
    }, { deep: true })

    async function validate() {
      if (!formData.value.name?.trim()) {
        throw new Error('字段名称不能为空')
      }
      if (!formData.value.type) {
        throw new Error('字段类型不能为空')
      }
      if (!formData.value.value?.trim()) {
        throw new Error('字段值不能为空')
      }
      return true
    }

    return {
      formData,
      validate
    }
  }
}
</script>

<style scoped>
.listener-field-inject {
  padding: 12px;
}
</style>